var express = require('express');
var router = express.Router();

const multer = require("multer");
const db = require('./db/db');
const { sendData } = require('./common/common');


const storage = multer.diskStorage({
    destination: "public/images/upload", 
    filename: function (req, file, cb) {
      var fileFormat = file.originalname.split(".");
      var filename = new Date().getTime();
      cb(null, filename + "." + fileFormat[fileFormat.length - 1]);
    },
  });
  // 上传对象
  const upload = multer({
    storage,
  });

  

/* GET home page. */
router.get('/', function (req, res, next) {
  res.send('添加好物商品模块')
});

// 图片上传
router.post("/upload", upload.single("file"), (req, res) => {
    let { filename } = req.file;
    console.log(filename);
    if(filename){
        sendData(res,0,'上传成功','/images/upload/'+filename)
    }else{
        sendData(res,1,'上传图片失败，检查file对象是否发送')
    }
  });


  //新增有品好物

router.post('/add', function (req, res, next) {
  let { title, img,type,current_price,old_price,tags,desc_text,userId} = req.body;
  if (userId&&title && img && type && current_price && old_price && tags && desc_text) {
    let sql = ` insert into perfect_goods (title,img,type,current_price,old_price,tags,desc_text) values('${title}','${img}','${type}','${current_price}','${old_price}','${tags}','${desc_text}')`;

    console.log(sql);

    db.query(sql, (err, data) => {
      if (data.affectedRows) {
        sendData(res, 0, '添加好物商品成功');
      } else {
        sendData(res, 1, '添加失败,数据库操作失败');
      }
    })
  } else {
    sendData(res, 0, '添加失败，数据传入不完整');
  }


});



module.exports = router;
